package com.egoo.ticket.server.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.WorkOrderDao;
import com.egoo.ticket.server.dao.WorkOrderTypeNodeDao;
import com.egoo.ticket.server.pojo.dto.SelectByNameAndTypeDto;
import com.egoo.ticket.server.pojo.dto.WorkOrderStatusInputDto;
import com.egoo.ticket.server.pojo.entity.WorkOrder;
import com.egoo.ticket.server.pojo.entity.WorkOrderStatus;
import com.egoo.ticket.server.pojo.vo.WorkOrderStatusListVo;
import com.egoo.ticket.server.pojo.vo.WorkOrderTypeNodeVo;
import com.egoo.ticket.server.service.WorkOrderStatusService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.DbResponse;
import com.egoo.ticket.server.utils.common.ResponseConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @author Donny_Dong
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/workOrderStatus", produces = "application/json")
@Api(value = "工单状态管理",tags = "工单状态管理",description = "工单状态管理")
public class WorkOrderStatusController {

	@Autowired
	private WorkOrderStatusService workOrderStatusService;
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private WorkOrderTypeNodeDao workOrderTypeNodeDao;

	@ApiOperation(value = "根据id获取工单状态", notes = "根据id获取工单状态")
	@RequestMapping(method = RequestMethod.GET, value = "/selectById")
	public DbResponse selectById(@ApiParam(value = "id", required = true) @RequestParam(name = "id") Integer id,
								 HttpServletRequest request) {
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse();
		WorkOrderStatus workOrderStatus = workOrderStatusService.selectById(id,tenantId);
		dbResponse.setRetCode(200);
		dbResponse.setData(workOrderStatus);
		return dbResponse;
	}

	@ApiOperation(value = "根据状态名称获取工单状态信息", notes = "根据状态名称获取工单状态信息")
	@RequestMapping(method = RequestMethod.POST, value = "/selectByName")
	public DbResponse selectByName(@ApiParam(value = "selectByName") @RequestBody SelectByNameAndTypeDto selectByNameAndTypeDto,
								   HttpServletRequest request){

		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse();
		String name = selectByNameAndTypeDto.getName();
		Integer currentPage = selectByNameAndTypeDto.getCurrentPage();
		Integer pageSize = selectByNameAndTypeDto.getPageSize();
		try {
			return  workOrderStatusService.selectByName(name, currentPage, pageSize, tenantId);
		}catch (Exception e){
			log.info("根据状态名称获取工单状态信息:"+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,
					ResponseConstant.SELECT_FAIL_MSG,"根据状态名称获取工单状态信息:"+e);
		}

	}

	@ApiOperation(value = "根据状态名称获取工单状态信息(不包含状态不变)", notes = "根据状态名称获取工单状态信息(不包含状态不变)")
	@RequestMapping(method = RequestMethod.POST, value = "/selectByNameNotContainNotNoChanging")
	public DbResponse selectByNameNotContainNotNoChanging(@ApiParam(value = "selectByNameNotContainNotNoChanging") @RequestBody SelectByNameAndTypeDto selectByNameAndTypeDto,
														  HttpServletRequest request){
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		String name = selectByNameAndTypeDto.getName();
		Integer currentPage = selectByNameAndTypeDto.getCurrentPage();
		Integer pageSize = selectByNameAndTypeDto.getPageSize();
		try {
			return workOrderStatusService.selectByNameNotContainNotNoChanging(name, currentPage, pageSize,tenantId);
		}catch (Exception e){
			log.info("根据状态名称获取工单状态信息(不包含状态不变)异常："+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"根据状态名称获取工单状态信息(不包含状态不变)异常："+e);
		}

	}


	@ApiOperation(value = "新建工单状态", notes = "新建工单状态")
	@RequestMapping(method = RequestMethod.POST, value = "/createWorkOrderStatus")
	public DbResponse createWorkOrderStatus(@ApiParam(value = "createWorkOrderStatus", required = true) @RequestBody WorkOrderStatusInputDto workOrderStatusInputDto,
											HttpServletRequest request) {
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "新建失败");
		String name = workOrderStatusInputDto.getName();
		Integer ordering = workOrderStatusInputDto.getOrdering();
		String userId = workOrderStatusInputDto.getUserId();
		WorkOrderStatus workOrderStatus = workOrderStatusService.selectByEqualsName(name,tenantId);
		if (workOrderStatus != null) {
			dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
			dbResponse.setMsg("状态名称已存在");
			return dbResponse;
		}
		if(StringUtils.isBlank(name) || null == name){
			dbResponse.setMsg("状态名称不能为空");
			return dbResponse;
		}else {
			if(name.length()> ConstantCode.ControllerStrLengthCheck.LENGTH){
				dbResponse.setMsg("状态名称不能超过80个字");
				return dbResponse;
			}
		}
		WorkOrderStatus workOrderStatus1 = workOrderStatusService.selectByOrdering(ordering);
		if (workOrderStatus1 != null) {
			dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
			dbResponse.setMsg("状态排序已存在");
			return dbResponse;
		}
		int retCode = workOrderStatusService.insertStatus(name, ordering, userId,tenantId);
		if (retCode == ResponseConstant.RESULT_SUCCESS) {
			dbResponse.setRetCode(200);
			dbResponse.setMsg("新建成功");
		}
		return dbResponse;
	}

	@ApiOperation(value = "编辑工单状态", notes = "根据状态名称与排序更新工单状态信息")
	@RequestMapping(value = "/updateWorkOrderStatus", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public DbResponse updateWorkOrderStatus(@ApiParam(value = "updateWorkOrderStatus", required = true) @RequestBody WorkOrderStatusInputDto workOrderStatusInputDto,
											HttpServletRequest request) {
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "编辑失败");
		Integer id = workOrderStatusInputDto.getId();
		String name = workOrderStatusInputDto.getName();
		Integer ordering = workOrderStatusInputDto.getOrdering();
		String userId = workOrderStatusInputDto.getUserId();
		WorkOrderStatus workOrderStatus = workOrderStatusService.selectById(id,tenantId);
		if (workOrderStatus != null) {
			if(StringUtils.isBlank(name) || null == name){
				dbResponse.setMsg("状态名称不能为空");
				return dbResponse;
			}else {
				if(name.length()> ConstantCode.ControllerStrLengthCheck.LENGTH){
					dbResponse.setMsg("状态名称不能超过80个字");
					return dbResponse;
				}
			}
			if (workOrderStatus.getName().equals(name) && workOrderStatus.getOrdering().equals(ordering)) {
				workOrderStatus.setName(name);
				workOrderStatus.setOrdering(ordering);
				int retCode = workOrderStatusService.updateStatus(workOrderStatus, userId);
				if (retCode == ResponseConstant.RESULT_SUCCESS) {
					dbResponse.setRetCode(200);
					dbResponse.setMsg("编辑成功");
				}
				return dbResponse;
			}
			if (workOrderStatus.getName().equals(name) && !workOrderStatus.getOrdering().equals(ordering)) {
				WorkOrderStatus workOrderStatus2 = workOrderStatusService.selectByOrdering(ordering);
				if (workOrderStatus2 != null) {
					dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
					dbResponse.setMsg("状态排序已存在");
					return dbResponse;
				}
				workOrderStatus.setName(name);
				workOrderStatus.setOrdering(ordering);
				int retCode = workOrderStatusService.updateStatus(workOrderStatus, userId);
				if (retCode == ResponseConstant.RESULT_SUCCESS) {
					dbResponse.setRetCode(200);
					dbResponse.setMsg("编辑成功");
				}
				return dbResponse;

			}
			if (!workOrderStatus.getName().equals(name) && workOrderStatus.getOrdering().equals(ordering)) {
				WorkOrderStatus workOrderStatus1 = workOrderStatusService.selectByEqualsName(name,tenantId);
				if (workOrderStatus1 != null) {
					dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
					dbResponse.setMsg("状态名称已存在");
					return dbResponse;
				}
				workOrderStatus.setName(name);
				workOrderStatus.setOrdering(ordering);
				int retCode = workOrderStatusService.updateStatus(workOrderStatus, userId);
				if (retCode == ResponseConstant.RESULT_SUCCESS) {
					dbResponse.setRetCode(200);
					dbResponse.setMsg("编辑成功");
				}
				return dbResponse;
			}
			if (!workOrderStatus.getName().equals(name) && !workOrderStatus.getOrdering().equals(ordering)) {
				WorkOrderStatus workOrderStatus1 = workOrderStatusService.selectByEqualsName(name,tenantId);
				if (workOrderStatus1 != null) {
					dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
					dbResponse.setMsg("状态名称已存在");
					return dbResponse;
				}
				WorkOrderStatus workOrderStatus2 = workOrderStatusService.selectByOrdering(ordering);
				if (workOrderStatus2 != null) {
					dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
					dbResponse.setMsg("状态排序已存在");
					return dbResponse;
				}
				workOrderStatus.setName(name);
				workOrderStatus.setOrdering(ordering);
				int retCode = workOrderStatusService.updateStatus(workOrderStatus, userId);
				if (retCode == ResponseConstant.RESULT_SUCCESS) {
					dbResponse.setRetCode(200);
					dbResponse.setMsg("编辑成功");
				}
				return dbResponse;

			}
		}
		dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
		dbResponse.setMsg("没有该工单状态");
		return dbResponse;
	}

	@ApiOperation(value = "删除工单状态", notes = "根据id删除工作状态")
	@RequestMapping(value = "/deleteWorkOrderStatus", method = RequestMethod.DELETE, produces = "application/json")
	@ResponseBody
	public DbResponse deleteWorkOrderStatus(@ApiParam(value = "状态ID", required = true) @RequestParam("id") Integer id,
											HttpServletRequest request) {
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "删除失败");
		WorkOrderStatus workOrderStatus = workOrderStatusService.selectById(id,tenantId);
		List<WorkOrder> workOrderList = workOrderDao.selectByStatusId(id);
		boolean b = checkStateIsUsed(id);
		if(b){
			dbResponse.setMsg("该状态在流程中被使用，不能删除");
			return dbResponse;
		}
		if (null!=workOrderList && workOrderList.size()>0){
			dbResponse.setMsg("有工单正在使用该状态，请先转移该状态下的工单");
			return  dbResponse;
		}

		if (workOrderStatus != null) {
			if (workOrderStatus.getTag().equals(0)) {
				int retCode = workOrderStatusService.deleteStatus(id,tenantId);
				if (retCode == ResponseConstant.RESULT_SUCCESS) {
					dbResponse.setRetCode(200);
					dbResponse.setMsg("删除成功");
				}
				return dbResponse;
			}
			dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
			dbResponse.setMsg("无法删除该工单状态");
			return dbResponse;
		}
		dbResponse.setRetCode(ResponseConstant.RES_FAIL_CODE);
		dbResponse.setMsg("没有该工单状态，无法删除");
		return dbResponse;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 判断状态是否在流程中被使用
	 * @Param:
	 * @return:
	 * @Date: 2020/7/29
	 */
	private boolean checkStateIsUsed(Integer id) {
		List<WorkOrderTypeNodeVo> allLatestNodes = workOrderTypeNodeDao.getAllLatestNodes();
		HashSet<Integer> integers = new HashSet<>();
		for (WorkOrderTypeNodeVo workOrderTypeNodeVo:allLatestNodes
			 ) {
			JSONArray sequenceFlows = workOrderTypeNodeVo.getContent().getJSONArray("sequenceFlows");
			if (CollectionUtils.isEmpty(sequenceFlows)){
				continue;
			}
			for (int i = 0; i < sequenceFlows.size(); i++) {
				JSONObject jsonObject = sequenceFlows.getJSONObject(i);
				Integer status = jsonObject.getInteger("status");
				integers.add(status);
			}
		}
		if (integers.contains(id)){
			return true;
		}
		return false;
	}

	@ApiOperation(value = "提供默认状态排序值", notes = "提供默认状态排序值")
	@RequestMapping(value = "/selectOrder", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public DbResponse selectOrder(HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse();
		int retCode = workOrderStatusService.selectOrderMax(tenantId);
		dbResponse.setRetCode(200);
		dbResponse.setData(retCode);
		return dbResponse;
	}


	@ApiOperation(value = "获取所有的工单状态信息", notes = "获取所有的工单状态信息")
	@RequestMapping(method = RequestMethod.GET, value = "/selectAll")
	public DbResponse selectAll(HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse();
		List<WorkOrderStatus> workOrderStatusList = workOrderStatusService.selectAll(tenantId);
		dbResponse.setRetCode(200);
		dbResponse.setData(workOrderStatusList);
		return dbResponse;
	}

	@ApiOperation(value = "获取全部(包含状态不变)的工单状态信息", notes = "获取全部(包含状态不变)的工单状态信息")
	@RequestMapping(method = RequestMethod.GET, value = "/selectAllStatus")
	public DbResponse selectAllStatus(HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);
		DbResponse dbResponse = new DbResponse();
		List<WorkOrderStatus> workOrderStatusList = new ArrayList<>();
		WorkOrderStatus workOrderStatus = new WorkOrderStatus();
		workOrderStatus.setId(0);
		workOrderStatus.setName("状态不变");
		workOrderStatusList.add(workOrderStatus);
		List<WorkOrderStatus> workOrderStatusList1 = workOrderStatusService.selectAll(tenantId);
		workOrderStatusList.addAll(workOrderStatusList1);
		dbResponse.setRetCode(200);
		dbResponse.setData(workOrderStatusList);
		return dbResponse;
	}

	@ApiOperation(value = "对工单状态信息进行分页查询", notes = "对工单状态信息进行分页查询")
	@RequestMapping(method = RequestMethod.GET, value = "/selectAllPage")
	public DbResponse selectAllPage(@ApiParam(value = "当前页", required = true) @RequestParam("currentPage") Integer currentPage,
									@ApiParam(value = "每页行数", required = true) @RequestParam("pageSize") Integer pageSize,
									HttpServletRequest request) {
		String userId = request.getHeader(ConstantCode.CurrentUserInfo.USER_ID);
		String tenantId = request.getHeader(ConstantCode.CurrentUserInfo.TENANT_ID);

		DbResponse dbResponse = new DbResponse(ResponseConstant.RES_FAIL_CODE, "分页失败");
		WorkOrderStatusListVo workOrderStatusListVo = new WorkOrderStatusListVo();
		List<WorkOrderStatus> workOrderStatusList
				= workOrderStatusService.selectAll(tenantId);
		int totalCount = workOrderStatusList.size();
		List<WorkOrderStatus> workOrderStatusList1
				= workOrderStatusService.listPageAllWorkOrderStatus(currentPage, pageSize,tenantId);
		if (workOrderStatusList1 != null && !workOrderStatusList1.isEmpty()) {
			workOrderStatusListVo.setTotalCount(totalCount);
			workOrderStatusListVo.setWorkOrderStatusList(workOrderStatusList1);
			dbResponse.setRetCode(200);
			dbResponse.setData(workOrderStatusListVo);
			dbResponse.setMsg("分页成功");
		}
		return dbResponse;

	}
	
	@ApiOperation(value = "获取工单类型节点操作按钮", notes = "获取工单类型节点操作按钮")
	@RequestMapping(method = RequestMethod.GET, value = "/getWorkTypeNodeButton")
	public DbResponse getWorkTypeNodeButton(@ApiParam(value = "状态Id", required = true) @RequestParam("statusId")Integer statusId) {
		if (null ==statusId) {
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,"状态Id不存在");
		}
		try {
			
			JSONArray jsonArray = workOrderStatusService.getWorkTypeNodeButton(statusId);
			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE,ResponseConstant.SELECT_SUCCESS_MSG,jsonArray);
		} catch (Exception e) {
			
			log.info("获取工单类型节点操作按钮"+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE,ResponseConstant.SELECT_FAIL_MSG);
		}
	}
}
